package com.mspbots.ticketai.graderule;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mspbots.ticketai.GradeRuleInterceptorAdapter;
import com.mspbots.ticketai.model.Ticket;
import com.mspbots.ticketai.model.TicketRule;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Harry hou
 * @date 2019/11/18 10:26
 */
@Slf4j
@Service(value = "CONTACT_TITLE_POINT_RULE")
public class ContactTitleRuleInterceptor extends GradeRuleInterceptorAdapter {

    private static final String CONTACT = "contact";
    private List<ContactTitleRulesParams> contactTitleRulesParams;

    @Override
    public void prepare(TicketRule rule) {
        this.contactTitleRulesParams = this.objectMapper.convertValue(rule.getParams(), new TypeReference<List<ContactTitleRulesParams>>() {
        });
    }

    @Override
    public void process(Ticket ticket) {
        AtomicInteger order = new AtomicInteger();
        String ticketContactTile = ticket.getContactTitle();
        if (!StringUtils.isEmpty(ticketContactTile)) {
            contactTitleRulesParams.stream().filter(item -> item.selected)
                    .filter(item -> ticketContactTile.toLowerCase().contains(item.getTitle().toLowerCase()))
                    .forEach(item -> order.addAndGet(item.getPoints()));
        }
        ObjectNode orderDetailNode = ticket.getOrderDetail() == null ? objectMapper.createObjectNode() : ticket.getOrderDetail().deepCopy();
        ObjectNode jsonNodeParams = objectMapper.createObjectNode();
        jsonNodeParams.put("title", ticket.getContactTitle());
        jsonNodeParams.put("point", order.get());
        orderDetailNode.set(CONTACT, jsonNodeParams);
        ticket.setOrderDetail(orderDetailNode);
        ticket.setOrder(ticket.getOrder() + order.get());
    }

    @Data
    private static class ContactTitleRulesParams {
        private String title;
        private int points;
        private boolean selected;
    }
}
